package com.abigdreamer.im.client.module.talk.face;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import com.sun.imageio.plugins.gif.GIFImageMetadata;

public class GifUtil {

	public static GifFrame[] getFrames(File gifFile) throws IOException {
		final GifFrame[] frames;
		ImageReader reader = null;
		ImageInputStream imageIn = ImageIO.createImageInputStream(gifFile);
		Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("gif");
		if (iter.hasNext()) {
			reader = iter.next();
		}
		reader.setInput(imageIn, false);
		int count = reader.getNumImages(true);
		frames = new GifFrame[count];
		for (int i = 0; i < count; i++) {
			frames[i] = new GifFrame();
			frames[i].image = reader.read(i);
			frames[i].x = ((GIFImageMetadata) reader.getImageMetadata(i)).imageLeftPosition;
			frames[i].y = ((GIFImageMetadata) reader.getImageMetadata(i)).imageTopPosition;
			frames[i].width = ((GIFImageMetadata) reader.getImageMetadata(i)).imageWidth;
			frames[i].height = ((GIFImageMetadata) reader.getImageMetadata(i)).imageHeight;
			frames[i].disposalMethod = ((GIFImageMetadata) reader.getImageMetadata(i)).disposalMethod;
			frames[i].delayTime = ((GIFImageMetadata) reader.getImageMetadata(i)).delayTime;
		}
		
		return frames;
	}
}
